#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# @Time    : 2022/08/26 15:25
# @Author  : elegantfrog
# @FileName: client.py

from config import config
import paho.mqtt.client as mqtt
import paho.mqtt.subscribe as subscribe
import time
import json
import os
from utils import aUtils


class aMqtt():
    def __init__(self):
        self.HOST = config['mqtt']['host']
        self.PORT = config['mqtt']['port']
        self.USER = config['mqtt']['username']
        self.PWD = config['mqtt']['password']
        self.KEEPLIVE = 60
        self.client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        self.client = None
        self.pub_topic = 'seedlight/pub/'
        self.sub_topic = 'seedlight/sub/'
        self.utils = aUtils()
        self.path = '../files/config.json'

    def client_loop(self):
        self.client = mqtt.Client(self.client_id)  # ClientId不能重复，所以使用当前时间
        self.client.username_pw_set(self.USER, self.PWD)  # 必须设置，否则会返回「Connected with result code 4」
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.connect(self.HOST, self.PORT, self.KEEPLIVE)
        self.client.loop_forever()

    def on_connect(self, client, userdata, flags, rc):
        try:
            if rc == 0:
                print('mqtt server connection succeeded')
                with open(self.path, 'r') as f:
                    fileJson = json.load(f)
                res = self.utils.getDevCode(fileJson['files']['code'], 'r')
                print(res)
                self.sub_topic += res
                self.pub_topic += res
                client.subscribe(self.sub_topic)
            else:
                print("Connected with result code " + str(rc))
                print('mqtt server connection failed')
        except Exception as e:
            print(e)

    def on_publish(self, topic, data):
        try:
            self.client.publish(topic, data)
        except Exception as e:
            print(e)

    def on_message(self, client, userdata, msg):
        try:
            with open(self.path, 'r') as f:
                fileJson = json.load(f)
            print(fileJson)
            data = json.loads(msg.payload.decode("utf-8"))
            if data['method'] == 'd0':
                res = self.utils.operateCommand(data)
                if res == 'success':
                    print('调用命令执行成功')
                    # self.on_publish(self.pub_topic, json.dumps({"data": 'test params'}))
                else:
                    print('调用命令执行失败，请重试')
            elif data['method'] == 'd1':
                res = self.utils.setDevParams(fileJson['files']['light'], data['params'], fileJson['files'])
                if res['status'] == 'success':
                    print('光模组状态设置成功')
                    payload = {
                        'method': 'u1',
                        'params': res['data']
                    }
                    self.on_publish(self.pub_topic, json.dumps(payload))
                else:
                    print('光模组状态设置失败，请重试')
            elif data['method'] == 'd2':
                res = aUtils().getDevParams(fileJson['files'])
                payload = {
                    'method': 'u1',
                    'params': res['data']
                }
                self.on_publish(self.pub_topic, json.dumps(payload))
            elif data['method'] == 'd3':
                res = self.utils.setDevParams(fileJson['files']['brightness'], data['params'], fileJson['files'])
                if res['status'] == 'success':
                    print('补光灯调节成功')
                    payload = {
                        'method': 'u1',
                        'params': res['data']
                    }
                    self.on_publish(self.pub_topic, json.dumps(payload))
                else:
                    print('补光灯调节失败，请重试')
            elif data['method'] == 'd4':
                try:
                    res = {
                        'method': 'u3',
                        'params': fileJson['workVal']
                    }
                    self.on_publish(self.pub_topic, json.dumps(res))
                    print('工作参数获取成功')
                except Exception as e:
                    print(e)
                    print('工作参数获取失败，请重试')
            elif data['method'] == 'd5':
                try:
                    res = {
                        'method': 'u4',
                        'params': fileJson['netVal']
                    }
                    self.on_publish(self.pub_topic, json.dumps(res))
                    print('网络参数获取成功')
                except Exception as e:
                    print(e)
                    print('网络参数获取失败，请重试')
            elif data['method'] == 'd6':
                res = self.utils.setDevParams(fileJson['files']['alarm'], data['params'], fileJson['files'])
                if res['status'] == 'success':
                    print('蜂鸣器状态更新成功')
                    payload = {
                        'method': 'u1',
                        'params': res['data']
                    }
                    self.on_publish(self.pub_topic, json.dumps(payload))
                else:
                    print('蜂鸣器状态更新失败，请重试')
            elif data['method'] == 'd7':
                res = self.utils.updateConfig(self.path, fileJson, data['params'])
                if res == 'success':
                    print('工作参数设置成功')
                else:
                    print('工作参数设置失败，请重试')
        except Exception as e:
            print(e)
            pass


if __name__ == '__main__':
    mqCli = aMqtt().client_loop()
